/**
 * app接口访问
 * lenovo
 * 正式服务器 http://www.haomiteam.com:8687/hm-area
 * 
 * 测试 http://192.168.1.128:8686/eplus
 * 192.168.123.3
 * 2016-11-17
 */
function GetNetWorkState() {
    var NetStateStr = '未知';
    var types = {};
    types[plus.networkinfo.CONNECTION_UNKNOW] = "未知";
    types[plus.networkinfo.CONNECTION_NONE] = "未连接网络";
    types[plus.networkinfo.CONNECTION_ETHERNET] = "有线网络";
    types[plus.networkinfo.CONNECTION_WIFI] = "WiFi网络";
    types[plus.networkinfo.CONNECTION_CELL2G] = "2G蜂窝网络";
    types[plus.networkinfo.CONNECTION_CELL3G] = "3G蜂窝网络";
    types[plus.networkinfo.CONNECTION_CELL4G] = "4G蜂窝网络";
    NetStateStr = types[plus.networkinfo.getCurrentType()];
    return NetStateStr;
};

(function($) {
	mui.plusReady(function() {
		if(plus.os.name == "iOS") {
			plus.screen.lockOrientation("portrait-primary");
			plus.navigator.setStatusBarBackground('#000');
			plus.navigator.setStatusBarStyle("UIStatusBarStyleBlackOpaque");
		}
	});
//	$.eplus_url="http://www.haomiteam.com:8687/hm-area";
	$.eplus_url="http://bmfw.zhysq.cn/hm-area/";
//	$.eplus_url="http://192.168.123.69:8687/hm-area";
//	$.eplus_url="http://192.168.123.3:8081/hm-area";
	$.mobileReg=/^(13[0-9]{9})|(14[0-9]{9})|(18[0-9]{9})|(15[0-9]{9})|(17[0-9]{9})$/;
	$.isConsole=true;
	$.epAppType = 'android';
	$.ep_app_platform = 'children_app';
	$.is_decrypt="";
	$.audioPath ='/common/showSound?filePath=';
	//提示信息
	$.consoleLog=function(str)
	{
		if($.isConsole){
			console.log(str);
		}
	}
	$.isEmpty=function(str) {
		return(!$.isNotEmpty(str));
	}
	$.isNotEmpty=function(str) {
		var result = false;
		if(str=="" || str==undefined || 　str=='undefined') {
			result = false;
		}else{
			result=true;
		}
		return result;
	}
	//正则表达式
	$.checkPattern=function(str,reg)
	{
		var flag = reg.test(str);
		$.consoleLog(str + reg + flag);
		return flag;
	}
	//身份证号码判断
	$.checkIdCard=function(id_card)
	{
		var res=$.validateIdCard(id_card);
		if(res == 0) {
			return true;
		} else {
			return false;
		}
	}
	$.getBirthday=function(idCard) {
		var birthday = "";
		if(idCard != null && idCard != "") {
			if(idCard.length == 15) {
				birthday = "19" + idCard.substr(6, 6);
			} else if(idCard.length == 18) {
				birthday = idCard.substr(6, 8);
			}
			birthday = birthday.replace(/(.{4})(.{2})/, "$1-$2-");
		}
		return birthday;
	}
	$.validateIdCard=function(id_card){
		var aCity = {
			11: "北京",12: "天津",13: "河北",14: "山西",15: "内蒙古",21: "辽宁",22: "吉林",23: "黑龙江",
			31: "上海",32: "江苏",33: "浙江",34: "安徽",35: "福建",36: "江西",
			37: "山东",41: "河南",42: "湖北",43: "湖南",44: "广东",45: "广西",
			46: "海南",50: "重庆",51: "四川",52: "贵州",53: "云南",54: "西藏",
			61: "陕西",62: "甘肃",63: "青海",64: "宁夏",65: "新疆",71: "台湾",81: "香港",82: "澳门",91: "国外"
		};
		var iSum = 0;
		var strIDno = id_card;
		var idCardLength = strIDno.length;
		if(!/^\d{17}(\d|x)$/i.test(strIDno) && !/^\d{15}$/i.test(strIDno))
			return 1; // 非法身份证号
		if(aCity[parseInt(strIDno.substr(0, 2))] == null)
			return 2; // 非法地区
		// 15位身份证转换为18位
		if(idCardLength == 15) {
			sBirthday = "19" + strIDno.substr(6, 2) + "-" +
				Number(strIDno.substr(8, 2)) + "-" +
				Number(strIDno.substr(10, 2));
			var d = new Date(sBirthday.replace(/-/g, "/"))
			var dd = d.getFullYear().toString() + "-" + (d.getMonth() + 1) +
				"-" + d.getDate();
			if(sBirthday != dd)
				return 3; // 非法生日
			strIDno = strIDno.substring(0, 6) + "19" + strIDno.substring(6, 15);
			strIDno = strIDno + GetVerifyBit(strIDno);
		}
		// 判断是否大于2078年，小于1900年
		var year = strIDno.substring(6, 10);
		if(year < 1900 || year > 2078)
			return 3; // 非法生日
		// 18位身份证处理
		// 在后面的运算中x相当于数字10,所以转换成a
		strIDno = strIDno.replace(/x$/i, "a");

		sBirthday = strIDno.substr(6, 4) + "-" + Number(strIDno.substr(10, 2)) +
			"-" + Number(strIDno.substr(12, 2));
		var d = new Date(sBirthday.replace(/-/g, "/"))
		if(sBirthday != (d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d
				.getDate()))
			return 3; // 非法生日
		// 身份证编码规范验证
		for(var i = 17; i >= 0; i--)
			iSum += (Math.pow(2, i) % 11) *
			parseInt(strIDno.charAt(17 - i), 11);
		if(iSum % 11 != 1)
			return 1; // 非法身份证号

		// 判断是否屏蔽身份证
		var words = new Array();
		words = new Array("11111119111111111", "12121219121212121");
		for(var k = 0; k < words.length; k++) {
			if(strIDno.indexOf(words[k]) != -1) {
				return 1;
			}
		}
		return 0;
	}
	$.alert4Msg=function(msg)
	{
		msg=msg||"亲，出错了";
		plus.nativeUI.toast(msg);
	}
	$.put_server_url=function(server_url){
		localStorage.setItem('$server_url', server_url);
	}
	$.project_url=function(){
		//var result=localStorage.getItem('$server_url') || $.eplus_url;
		var result=$.eplus_url;
		return result;
	}
	$.base_url=function()
	{
		return $.project_url()+"/app/load.do";
	}
	$.mui_alert=function(msg,fn)
	{
		msg=msg || "出错了";
		$.consoleLog("==msg==="+msg);
		mui.alert(msg,'温馨提示',fn);
	}
	$.mui_confirm=function(msg,array,fn)
	{
		msg=msg||"";
		var btnArray = array;
		mui.confirm(msg, '温馨提示', btnArray, function(e) {
			if(e.index == 0) {fn();}
		});
	}
	$.exitApp=function(fn)
	{
		plus.nativeUI.actionSheet({
			title: "确定要退出?",
			cancel: "取消",
			buttons: [{title: "退出"}]
		}, function(b) {
			switch (b.index) {
				case 0:
					break;
				case 1:
					fn();
					break;
				default:
					break
			}
		});
	}
	//页面跳转
	$.showPage=function(id,extras) {
		var w_view=mui.openWindow({
			id: id,
			url: id+".html",
			styles: {popGesture: "none"},
			extras: {app:extras},  //配置参数
			createNew:true,
			show: {aniShow: "zoom-fade-in"},
			show:{
		      autoShow:true,
		      aniShow:"slide-in-right",
		      duration:200
		    },
			waiting: {
				autoShow: false
			}
		});
	}
	$.prePage=function(pageid,extras)
	{
		var mainPage = mui.preload({
			id: pageid,
			url: pageid+".html",
			styles: {popGesture: "none"},
			extras: {app:extras},
			show: {aniShow: "zoom-fade-out"},
			waiting: {
				autoShow: false
			}
		});
		var main_loaded_flag = false;
		mainPage.addEventListener("loaded",function () {
			main_loaded_flag = true;
		});
		var toMain = function() {
			//使用定时器的原因：
			//可能执行太快，main页面loaded事件尚未触发就执行自定义事件，此时必然会失败
			var id = setInterval(function () {
				if(main_loaded_flag){
					clearInterval(id);
	//				mui.fire(mainPage, 'show', null);
					mainPage.show("pop-in");
				}
			},20);
		};
	}
	//记住用户信息
	$.putUserName=function(userName)
	{
		userName=userName||''; 
		localStorage.setItem('$userName', userName);
	}
	$.getUserName=function(){
		return localStorage.getItem('$userName') || "";
	}
	//用户信息
	$.getUser=function(){
		return JSON.parse(localStorage.getItem('$user') || "{}");
	}
	$.putUser=function(user_json){
		localStorage.setItem('$user', JSON.stringify(user_json));
	}
	$.clearUser=function()
	{
		localStorage.removeItem("$user");
	}
	$.putSession=function(str){
		localStorage.setItem('$session_id', str);
	}
	$.getSession=function(){
		return localStorage.getItem('$session_id') || "";
	}
	$.ajax4Server=function(serviceKey,params,method,succ_callback,error_callback)
	{
		 $.consoleLog($.base_url());
		 $.consoleLog(JSON.stringify(params));
		 params=params||{};
		 mui.ajax($.base_url(),{
	        type:method,
	        timeout:60000,
	        data:params,
	        data: {
				serviceKey: "appService."+serviceKey,
				jsonConditionStr: JSON.stringify(params),
				is_decrypt: $.is_decrypt
			},
	        dataType: 'json', //服务器返回json格式数据
	        success:function(data){
	        			
				
	        	var code=data.code || 0;
	        	if(code==0){
	        		plus.nativeUI.closeWaiting();
					$.mui_alert("账号在其他终端登录,请重新登录!",function(){$.showPage("login",{});});
	        	}else{
	        		 succ_callback(data);
	        	}
	        },
			error:function(xhr,type,errorThrown){
				plus.nativeUI.closeWaiting();
				//alert4Msg("无法连接到网络",3);
				if(error_callback){
					error_callback("无法连接到网络");
				}
			}
	    });
	}
	//get
	$.ajax4Get=function(serviceKey,params,succ_callback,error_callback)
	{
		$.ajax4Server(serviceKey,params,"get",succ_callback,error_callback)
	}
	//post
	$.ajax4Post=function(serviceKey,params,succ_callback,error_callback)
	{	
		$.ajax4Server(serviceKey,params,"post",succ_callback,error_callback)
	}
    //------------------------------------服务器接口 start----------------------------------
	//登录
	$.appLogin=function(params,succ_callback,error_callback){
		params=params||{};
		var postParams={};
		postParams["mobile"]=params["mobile"];//账号
		postParams["password"]=params["password"];//密码
		var serviceKey="appLogin";
		$.ajax4Post(serviceKey,params,function(res){
			if(res.result){
				$.putUser(res.data);
				$.putSession(res.session_id);
			}
			succ_callback(res);
		},error_callback);
	}
	
	//验证码发送
	$.sendMobileCode=function(params,succ_callback,error_callback){
		params=params||{};
		var postParams={};
		postParams["mobile"]=params["mobile"];//手机号码
		var serviceKey="appSendMobileCode";
		
		$.ajax4Post(serviceKey,params,function(res){
			if(res.result){
				$.putUser(res.data);
				$.putSession(res.session_id);
			}
			succ_callback(res);
		},error_callback);
	}
	//注册
	$.appRegister=function(params,succ_callback,error_callback){
		params=params||{};
		var postParams={};
		postParams["mobile"]=params["mobile"];//手机号码
		postParams["mobileCode"]=params["mobileCode"];//手机验证码
		postParams["password"]=params["password"];//密码
		var serviceKey="appRegister";
		$.ajax4Post(serviceKey,params,function(res){
			if(res.result){
				$.putUser(res.data);
				$.putSession(res.session_id);
			}
			succ_callback(res);
		},error_callback);
	}
	
	//找回密码
	$.forgetPassword=function(params,succ_callback,error_callback){
		params=params||{};
		var postParams={};
		postParams["mobile"]=params["mobile"];//手机号码
		postParams["mobileCode"]=params["mobileCode"];//手机验证码
		postParams["password"]=params["password"];//密码
		var serviceKey="appForgetPassword";
		$.ajax4Post(serviceKey,params,function(res){
			if(res.result){
				$.putUser(res.data);
				$.putSession(res.session_id);
			}
			succ_callback(res);
		},error_callback);
	}
	
	//找回密码
	$.appModifyPassword=function(params,succ_callback,error_callback){
		params=params||{};
		var postParams={};
		postParams["mobile"]=params["mobile"];//手机号码
		postParams["password"]=params["password"];//密码
		postParams["newPassword"]=params["newPassword"];//新密码
		var serviceKey="appModifyPassword";
		$.ajax4Post(serviceKey,params,function(res){
			if(res.result){
				$.putUser(res.data);
				$.putSession(res.session_id);
			}
			succ_callback(res);
		},error_callback);
	}
	
	//修改个人信息
	$.personInfo=function(params,succ_callback,error_callback){
		params=params||{};
		var postParams={};
		postParams["sysChildrenId"]=params["sysChildrenId"];//child ID
		postParams["mobile"]=params["mobile"];//手机号
		postParams["trueName"]=params["trueName"];//姓名
		postParams["idCard"]=params["idCard"];//身份证
		postParams["csrq"]=params["csrq"];//出生日期
		postParams["cityCode"]=params["cityCode"];//省会
		postParams["areaCode"]=params["areaCode"];//城市
		postParams["townCode"]=params["townCode"];//区县
		postParams["streetCode"]=params["streetCode"];//街道
		postParams["buildingCode"]=params["buildingCode"];//楼别
		postParams["roomCode"]=params["roomCode"];//编号
		postParams["communityCode"]=params["communityCode"];//社区码
		var serviceKey="personInfo";
		$.ajax4Post(serviceKey,params,function(res){
			if(res.result){
				$.putUser(res.data);
				$.putSession(res.session_id);
			}
			succ_callback(res);
		},error_callback);
	}
	
	//绑定子女和老人
	$.bindOldManAndChildren=function(params,succ_callback,error_callback){
		params=params||{};
		var postParams={};
		postParams["sysChildrenId"]=params["sysChildrenId"];//child ID
		postParams["trueName"]=params["trueName"];//姓名
		postParams["idCard"]=params["idCard"];//身份证
		postParams["childrenIdCardPhoto1"]=params["childrenIdCardPhoto1"];//身份证1
		postParams["childrenIdCardPhoto2"]=params["childrenIdCardPhoto2"];//身份证2
		postParams["oldManName"]=params["oldManName"];//老人姓名
		postParams["oldManIdCard"]=params["oldManIdCard"];//老人身份证
		postParams["oldManMobile"]=params["oldManMobile"];//老人手机号
		postParams["oldmanIdCardPhoto1"]=params["oldmanIdCardPhoto1"];//身份证1
		postParams["oldmanIdCardPhoto2"]=params["oldmanIdCardPhoto2"];//身份证2		
		var serviceKey="bindOldManAndChildren";
		$.ajax4Post(serviceKey,params,function(res){
			if(res.result){
				$.putUser(res.data);
				$.putSession(res.session_id);
			}
			succ_callback(res);
		},error_callback);
	}
	
	//获取个人信息
	$.getPersonInfo=function(params,succ_callback,error_callback){
		params=params||{};
		var postParams={};
		postParams["sysChildrenId"]=params["sysChildrenId"];//child ID
		var serviceKey="getPersonInfo";
		$.ajax4Post(serviceKey,params,function(res){
			if(res.result){
				$.putUser(res.data);
				$.putSession(res.session_id);
			}
			succ_callback(res);
		},error_callback);
	}
	
	
	//获取老人信息
	$.bingOldManList=function(params,succ_callback,error_callback){
		params=params||{};
		var postParams={};
		postParams["sysChildrenId"]=params["sysChildrenId"];//child ID
		var serviceKey="bingOldManList";
		$.ajax4Post(serviceKey,params,function(res){
			if(res.result){
				$.putUser(res.data);
				$.putSession(res.session_id);
			}
			succ_callback(res);
		},error_callback);
	}
	//获取老人位置
	$.oldManLocaltion=function(params,succ_callback,error_callback){
		params=params||{};
		var postParams={};
		postParams["oldManId"]=params["oldManId"];//老人ID
		postParams["imei"]=params["imei"];//老人定位器imei	
		postParams["minDate"]=params["minDate"];//开始时间
		postParams["maxDate"]=params["maxDate"];//结束时间
		var serviceKey="oldManLocaltion";
		$.ajax4Post(serviceKey,params,function(res){
			if(res.result){
				$.putUser(res.data);
				$.putSession(res.session_id);
			}
			succ_callback(res);
		},error_callback);
	}
	//发送语音
	$.soundUpload=function(params,succ_callback,error_callback){
		params=params||{};
		var postParams={};
		postParams["soundName"]=params["soundName"];//soundName
		postParams["sysChildrenId"]=params["sysChildrenId"];//child ID
		postParams["oldManId"]=params["oldManId"];//家长id
		postParams["soundData"]=params["soundData"];//语音base64	
		var serviceKey="soundUpload";
		$.ajax4Post(serviceKey,params,function(res){
			if(res.result){
				$.putUser(res.data);
				$.putSession(res.session_id);
			}
			succ_callback(res);
		},error_callback);
	}
	
	//接收语音
	$.soundList=function(params,succ_callback,error_callback){
		params=params||{};
		var postParams={};
		postParams["sysChildrenId"]=params["sysChildrenId"];//child ID
		postParams["oldManId"]=params["oldManId"];//家长id
		postParams["pageNo"]=params["pageNo"];//页数	
		postParams["pageSize"]=params["pageSize"];//每页数量
		var serviceKey="soundList";
		$.ajax4Post(serviceKey,params,function(res){
			if(res.result){
				$.putUser(res.data);
				$.putSession(res.session_id);
			}
			succ_callback(res);
		},error_callback);
	}
	
	//获取摄像头列表
	$.videoList=function(params,succ_callback,error_callback){
		params=params||{};
		var postParams={};
		postParams["sysChildrenId"]=params["sysChildrenId"];//child ID
		var serviceKey="videoList";
		$.ajax4Post(serviceKey,params,function(res){
			if(res.result){
				$.putUser(res.data);
				$.putSession(res.session_id);
			}
			succ_callback(res);
		},error_callback);
	}
	
	//	控制摄像头方向
	//	direction 操作命令：0-上，1-下，2-左，3-右，4-左上，5-左下，6-右上，7-右下，8-放大，9-缩小，10-近焦距，11-远焦距
	$.videoControl=function(params,succ_callback,error_callback){
		params=params||{};
		var postParams={};
		postParams["sysVideoId"]=params["sysVideoId"];//video ID
		postParams["direction"]=params["direction"];//video ID
		
		var serviceKey="videoControl";
		$.ajax4Post(serviceKey,params,function(res){
			if(res.result){
				$.putUser(res.data);
				$.putSession(res.session_id);
			}
			succ_callback(res);
		},error_callback);
	}
	
	//设置声音已读
	$.soundRead=function(params,succ_callback,error_callback){
		params=params||{};
		var postParams={};
		postParams["soundId"]=params["soundId"];//语音 ID		
		var serviceKey="soundRead";
		$.ajax4Post(serviceKey,params,function(res){
			if(res.result){
				$.putUser(res.data);
				$.putSession(res.session_id);
			}
			succ_callback(res);
		},error_callback);
	}
	
	//查询市
	$.cityList=function(params,succ_callback,error_callback){
		params=params||{};
		var postParams={};
		postParams["cityId"]=params["cityId"];//cityId	
		var serviceKey="cityList";
		$.ajax4Post(serviceKey,params,function(res){
			if(res.result){
				$.putUser(res.data);
				$.putSession(res.session_id);
			}
			succ_callback(res);
		},error_callback);
	}
	
	//查询区县
	$.areaList=function(params,succ_callback,error_callback){
		params=params||{};
		var postParams={};
		postParams["cityCode"]=params["cityCode"];//cityCode	
		var serviceKey="areaList";
		$.ajax4Post(serviceKey,params,function(res){
			if(res.result){
				$.putUser(res.data);
				$.putSession(res.session_id);
			}
			succ_callback(res);
		},error_callback);
	}
	
	//查询街道
	$.townList=function(params,succ_callback,error_callback){
		params=params||{};
		var postParams={};
		postParams["cityCode"]=params["cityCode"];//cityCode	
		postParams["areaCode"]=params["areaCode"];//areaCode	
		var serviceKey="townList";
		$.ajax4Post(serviceKey,params,function(res){
			if(res.result){
				$.putUser(res.data);
				$.putSession(res.session_id);
			}
			succ_callback(res);
		},error_callback);
	}
	
	//查询路
	$.streetList=function(params,succ_callback,error_callback){
		params=params||{};
		var postParams={};
		postParams["cityCode"]=params["cityCode"];//cityCode	
		postParams["areaCode"]=params["areaCode"];//areaCode	
		postParams["townCode"]=params["townCode"];//areaCode	
		var serviceKey="streetList";
		$.ajax4Post(serviceKey,params,function(res){
			if(res.result){
				$.putUser(res.data);
				$.putSession(res.session_id);
			}
			succ_callback(res);
		},error_callback);
	}
	
	//查询楼
	$.bulidingList=function(params,succ_callback,error_callback){
		params=params||{};
		var postParams={};
		postParams["cityCode"]=params["cityCode"];//cityCode	
		postParams["areaCode"]=params["areaCode"];//areaCode	
		postParams["townCode"]=params["townCode"];//townCode	
		postParams["streetCode"]=params["streetCode"];//streetCode	
		var serviceKey="bulidingList";
		$.ajax4Post(serviceKey,params,function(res){
			if(res.result){
				$.putUser(res.data);
				$.putSession(res.session_id);
			}
			succ_callback(res);
		},error_callback);
	}
	
	//查询房
	$.roomList=function(params,succ_callback,error_callback){
		params=params||{};
		var postParams={};
		postParams["cityCode"]=params["cityCode"];//cityCode	
		postParams["areaCode"]=params["areaCode"];//areaCode	
		postParams["townCode"]=params["townCode"];//townCode	
		postParams["streetCode"]=params["streetCode"];//streetCode	
		postParams["buildingCode"]=params["buildingCode"];//streetCode	
		var serviceKey="roomList";
		$.ajax4Post(serviceKey,params,function(res){
			if(res.result){
				$.putUser(res.data);
				$.putSession(res.session_id);
			}
			succ_callback(res);
		},error_callback);
	}
	
	//查询社区
	$.communityList=function(params,succ_callback,error_callback){
		params=params||{};
		var postParams={};
		postParams["cityCode"]=params["cityCode"];//cityCode	
		postParams["areaCode"]=params["areaCode"];//areaCode	
		postParams["townCode"]=params["townCode"];//townCode	
		postParams["streetCode"]=params["streetCode"];//streetCode	
		var serviceKey="communityList";
		$.ajax4Post(serviceKey,params,function(res){
			if(res.result){
				$.putUser(res.data);
				$.putSession(res.session_id);
			}
			succ_callback(res);
		},error_callback);
	}
	
	
	//检测app版本	
	$.versionCheck=function(params,succ_callback,error_callback){
		params=params||{};
		var postParams={};
		postParams["ep_app_platform"]=params["ep_app_platform"];//系统	
		postParams["epAppType"]=params["epAppType"];//epAppType	
		postParams["innerVersion"]=params["innerVersion"];//内部版本	
		postParams["epAppVersion"]=params["epAppVersion"];//epAppVersion	
		var serviceKey="versionCheck";
		$.ajax4Post(serviceKey,params,function(res){
			if(res.result){
				$.putUser(res.data);
				$.putSession(res.session_id);
			}
			succ_callback(res);
		},error_callback);
	}
	
	//联系方式
	$.getContact=function(params,succ_callback,error_callback){
		params=params||{};
		var postParams={};
		postParams["sysContactId"]=params["sysContactId"];//sysContactId	
		var serviceKey="getContact";
		$.ajax4Post(serviceKey,params,function(res){
			if(res.result){
				$.putUser(res.data);
				$.putSession(res.session_id);
			}
			succ_callback(res);
		},error_callback);
	}

	
	
//------------------------------------服务器接口 end----------------------------------

}(window.App= {}));
